package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constat.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @authou: fu
 * @date:Created in 2019/12/12
 * @description:
 * @version:1.0
 */
@Service
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Menu> page = menuDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Menu menu) {
        if (menu.getParentMenuId() == null){
            menu.setLevel(1);
            int priority =menu.getPriority()+1;
            menu.setPath(""+priority+"");
        }else {
            menu.setLevel(2);
            Integer priority = menu.getPriority();
            Integer parentMenuId = menu.getParentMenuId();
            Menu menu1 = menuDao.findParentMenuIdById(parentMenuId);
            String path = menu1.getPath();
            menu.setPath("/"+ path +"-"+ priority);
        }
        menuDao.add(menu);
    }

    @Override
    public Menu findById(Integer id) {

        return menuDao.findById(id);
    }

    @Override
    public void edit(Menu menu) {
        if (menu.getParentMenuId() == null){
            menu.setLevel(1);
        }else {
            menu.setLevel(2);
        }
        menuDao.edit(menu);
    }

    @Override
    public void deleteById(Integer id) {
        long findCountByParentMenuId = menuDao.findCountByParentMenuId(id);
        if (findCountByParentMenuId>0){
            throw new RuntimeException(MessageConstant.MENUDELETEFAIL);
        }
        //查询当前菜单是否已经关联到角色
        long findCountByMenuId = menuDao.findCountByMenuId(id);
        if (findCountByMenuId>0){
            throw new RuntimeException(MessageConstant.MENUHASASSOCIATION);
        }
        menuDao.deleteById(id);
    }
    @Override
    public List<Menu> findListAll() {

        List<Menu> listAll = menuDao.findListAll();
        List<Menu> list = new ArrayList<>();
        for (Menu menu : listAll) {
            if (menu.getLevel()==1){
                list.add(menu);
            }
        }
        return list;
    }
}
